package br.edu.oxente.buzz.service.dumb;

import br.edu.oxente.buzz.entity.Buzz;
import br.edu.oxente.buzz.entity.Post;
import br.edu.oxente.buzz.entity.User;
import br.edu.oxente.buzz.service.OBServices;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Nigini A. Oliveira - ensino@nigini.com.br
 */
public class OBDumbFacade implements OBServices {

	private Map<String,Buzz> buzzes;

	public OBDumbFacade() {
		this.buzzes = new HashMap<String, Buzz>();
	}
	
	public boolean addUser(String login) {
		if( login == null || login.equals( "" ) || this.buzzes.keySet().contains( login ) ){
			return false;
		} else {
			User newUser = new User( login, "" );
			Buzz newBuzz = new Buzz( newUser );
			this.buzzes.put( login, newBuzz );
			return true;
		}
	}

	public boolean addPost( String login, String text ) {
		if( !this.buzzes.keySet().contains( login ) ){
			return false;
		}
		Buzz b = this.buzzes.get( login );
		Post newPost = new Post( b.getOwner(), text );
		b.insertPost( newPost );
		for( User follower : b.getFollowers() ) {
			this.buzzes.get( follower.getLogin() ).insertPost( newPost );
		}
		return true;
	}

	public List<String> listPosts(String login, int limit) {
		if( !this.buzzes.keySet().contains( login ) || limit < 0 ) {
			return null;
		}
		return this.getTextFromPosts( this.buzzes.get(login).getPosts( limit ) );
	}

	private List<String> getTextFromPosts( List<Post> posts ) {
		List<String> messages = new ArrayList<String>( posts.size() );
		for (Post post : posts) {
			messages.add( post.getText() );
		}
		return messages;
	}

	public boolean followUser(String login, String userToFollow) {
		if( !this.buzzes.keySet().contains( login ) || !this.buzzes.keySet().contains( userToFollow ) ) {
			return false;
		}
		Buzz userBuzz = this.buzzes.get(login);
		Buzz toFollowBuzz = this.buzzes.get( userToFollow );
		boolean sucess = true;
		sucess &= userBuzz.follow( toFollowBuzz.getOwner() );
		sucess &= toFollowBuzz.insertFollower( userBuzz.getOwner() );
		return sucess;
	}
}
